module ErrorMonitor

  def self.included(base)
    base.prepend_around_action :log_error
  end
  
  def log_error
    begin
      yield
    rescue Exception => e
        ErrorLogger.perform_async(request.path, 
                                  request.params, 
                                  current_user.try(:id), 
                                  Time.now,
                                  e.inspect,
                                  trace(e)) unless Rails.configuration.consider_all_requests_local

      raise e
    end
  end

  def trace(e)
    rails_root = Rails.root.to_s

    e.backtrace
     .select {|line| line.start_with?(rails_root)} 
     .map {|line| line.gsub(rails_root, '')}
     .join("\n")
  end
end
